#!/usr/bin/env python

import codecs
import sys
import os

myCodecList = ['shift-jis', 'gb2312', 'gbk']

def changeFile(path):
    global myCodecList
    datatmp = ''
    for index in myCodecList:
        filein = codecs.open(path, 'r', index)
        print('read file by code %s'%(index))
        try:
            datatmp = filein.read()
            filein.close()
            isFileLoaded = True
            break;
        except:
            print('file is not coded by %s'%(index))
            isFileLoaded = False;
            continue
            
    if False == isFileLoaded :
        return
    print('changeing %s file......'%path)
    fileout = codecs.open(path, 'w', 'utf-8')
    fileout.write(datatmp)
    fileout.close()
	
    print('closeing %s file......'%path)

def changeDir(path):
    if os.path.isdir(path):
        dirlist = os.listdir(path)
        for item in dirlist:
            changeDir("%s/%s"%(path, item))
    elif os.path.isfile(path):
        changeFile(path)
    else:
        print("changeDir argument error!")

if __name__ == '__main__':
    if os.path.isfile(sys.argv[-1]):
        changeFile(sys.argv[-1])
    elif os.path.isdir(sys.argv[-1]):
        changeDir(sys.argv[-1])
    else :
        printf("argument error!")
    
